package com.soos.utils;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

import static com.soos.utils.RedisConstants.*;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: sfx
 * Date: 2023-06-27
 * Time: 14:18
 */
@Slf4j
@Component
public class CacheClient {

    private StringRedisTemplate stringRedisTemplate;
    private final ExecutorService REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);
    public CacheClient(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }
    //将任意的Java对象序列化为JSON并存储在string类型的key中,并且可以设置TTL过期时间
    public void set(String key, Object val, Long time, TimeUnit unit) {
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(val),time,unit);
    }
    //将任意的Java对象序列化为JSON并存储在string类型的key中,并且可以设置逻辑过期时间,用于处理缓存击穿问题
    public void setLogicalExpireTime(String key, Object val, Long time, TimeUnit unit) {
        RedisData redisData = new RedisData();
        redisData.setData(JSONUtil.toJsonStr(val));
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(unit.toSeconds(time)));
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(val));
    }

    //根据指定的key查询缓存,并反序列化为指定类型,利用缓存控制的方式解决缓存穿透问题
    /**
     * 3.解决缓存穿透问题(cachePenetration缓存空对象 + 布隆过滤器)
     * 1.通过缓存空对象来解决缓存穿透问题
     */
    public <R,ID> R queryWithPassThrough(String keyPrefix, ID id, Class<R> type,
                                     Function<ID,R> dbFollBack, Long time, TimeUnit unit) {
        //1.查询redis
        String key = keyPrefix + id;
        String json = stringRedisTemplate.opsForValue().get(key + id);
        //2.如果传入的字符串去除两端空格后的长度大于 0，返回 true
        if(StrUtil.isNotBlank(json)) {
            //3.redis中有直接返回
            return JSONUtil.toBean(json,type);
        }
        //4.redis中有空对象,返回null
        if(json!=null) {
            return null;
        }
        //5.redis中没有,查询数据库
        R r = dbFollBack.apply(id);
        if(r == null) {
            //6.数据库中没有,缓存空对象,返回null
            stringRedisTemplate.opsForValue().set(key,"",CACHE_NULL_TTL,TimeUnit.MINUTES);
            return null;
        }
        //7.数据库中有,写入redis,返回商铺信息
        this.set(key,JSONUtil.toJsonStr(r),time,unit);
        return r;
    }

    //根据指定的key查询缓存,并反序列化为指定类型,需要利用逻辑过期解决缓存击穿问题
    /**
     * 尝试获取锁
     */
    private boolean tryLock(String key) {
        Boolean isSuccess = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", LOCK_SHOP_TTL, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(isSuccess);
    }
    /**
     * 释放锁
     * @param key
     */
    private void unlock(String key) {
        stringRedisTemplate.delete(key);
    }

    /**
     * 4.解决缓存击穿问题(cacheBreakdown互斥锁 + 逻辑过期)
     * 通过逻辑过期解决缓存击穿问题
     *    先要把热点key加载到redis中(缓存预热) + 并且要加上逻辑过期时间
     */
    public <R,ID> R queryWithLogicalExpire(String keyPrefix, ID id, Class<R> type,
                                           Function<ID,R> dbFollBack, Long time, TimeUnit unit) {
        //2.先获取缓存中的RedisData
        String key = keyPrefix + id;
        String json = stringRedisTemplate.opsForValue().get(key);
        RedisData redisData = JSONUtil.toBean(json, RedisData.class);
        JSONObject jsonObject = (JSONObject) redisData.getData();
        R r = JSONUtil.toBean(jsonObject, type);
        //3.判断商品信息是否过期
        LocalDateTime expireTime = redisData.getExpireTime();
        if(expireTime.isAfter(LocalDateTime.now())) {
            //4.没有过期,直接返回
            return r;
        }
        //4.过期,先要获取锁信息
        String lockKey = LOCK_SHOP_KEY + id;
        if(tryLock(lockKey)) {
            //6.获取锁成功,做double check
            if (expireTime.isAfter(LocalDateTime.now())) {
                //7.没有过期,直接返回
                return r;
            }
            //8.另外开启一个线程做缓存重建
            REBUILD_EXECUTOR.submit(() -> {
                try {
                    //做缓存重建
                    //1.查询数据库
                    R r1 = dbFollBack.apply(id);
                    //2.写入redis
                    this.setLogicalExpireTime(key,r1,time,unit);
                }finally {
                    //9.释放锁
                    unlock(lockKey);
                }
            });
        }
        //返回店铺信息,获取锁失败,直接返回旧的数据
        return r;
    }
}